﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Tools;

namespace ChatTool
{
    class ServerConnection
    {
        Socket server;
        string stringData;
        IPEndPoint ipEndPoint;
        byte[] data;
        private static NetworkStream networkStream;
        private static TcpClient tcpClient;
        private static TcpListener tcpListener;

        public ServerConnection()
        {
            ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11111);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            data = new byte[1024];
            tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 9050);
        }

        public void connectServer(String us, String pw)
        {
            if (!server.Connected)
            {
                try
                {
                    server.Connect(ipEndPoint);
                    MainApplication.dle.Invoke("Connected to Server!");

                    var listener = new Thread( () => Connect (us,pw)) ;

                    listener.Priority = ThreadPriority.Lowest;
                    listener.Start();
                }
                catch (Exception exception)
                {
                    MainApplication.dle.Invoke(exception.Message);
                }
            }
        }

        private void Connect(String Username, String PW)
        {
            data = "LOGIN".ToByteArray();
            networkStream = new NetworkStream(server);
            networkStream.Write(data, 0, data.Length);

            Thread.Sleep(1000);
            data = new byte[1024];

            String answer = getContent();
            MainApplication.dle.Invoke("Server responded: " + answer);
            switch (answer)
            {
                case "ACK":
                    data = ("ACK|" + Username + "|" + PW).ToByteArray();
                    networkStream.Write(data, 0, data.Length);
                    break;
                default:
                    MainApplication.dle.Invoke("Error: " + answer);
                    server.Close();
                    return;
            }

        }

        private String getContent()
        {
            String content = "";
            Thread.Sleep(10);
            while (server.Available > 0)
            {
                int bytes = server.Available;
                byte[] buffer = new byte[bytes];
                server.Receive(buffer, bytes, SocketFlags.None);
                content += Encoding.UTF8.GetString(buffer);
                Thread.Sleep(10);
            }
            return content;
        }

    }
}
